import { VxeUI } from 'vxe-pc-ui';
import router from '@/router';
import { useRoute } from 'vue-router';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { useComponentState } from '@/composables/useComponentState';
import { useTableResize } from '@/composables/useTableResize';
import { hasAuth } from '@/plugins/permission';
import { useTagsViewStore } from '@/store';
import { useVxeGridUtils } from '@/composables/useVxeGridUtils';
import { MenuTypeEnum, ResultEnum } from '@/enums';
import { useDBTableSelector } from '@/composables/useDBTableSelector';

export const useTable = (options) => {
  const {
    API, // 后端API
    FieldAPI, // 字段API
    tableId, // 表格ID
    customConfig = {}, // 自定义配置
  } = options;

  // 表格引用
  const gridRef = ref(); // vxe-grid 组件实例
  const gridOptions = ref({}); // vxe-grid 配置
  const gridEvents = ref({}); // vxe-grid 事件

  // 附属组件引用和状态
  const addRef = ref(); // 新增
  const updateRef = ref(); // 修改
  const detailRef = ref(); // 详情

  // 公共变量
  const selectOption = ref({}); // 选择框字典数据
  const showSearch = ref(false); // 是否显示搜索表单
  const {
    isLayoutDisabled, // 布局禁用状态
    isSelectionMode, // 弹窗或者跳转组件的选择模式
    isCheckboxMode, // 多选模式
    isChildrenMode, // 子组件模式
  } = useComponentState();
  const {
    tableHeight, // 表格高度
    formItemSpan, // 表单项栅格
  } = useTableResize(isLayoutDisabled);

  // 路由相关
  const route = useRoute(); // 当前路由
  const tagsViewStore = useTagsViewStore(); // 标签页
  const utils = useVxeGridUtils(); // 相关工具函数
  const { renderToolbarButton, renderToolbarTool } = useVxeGridUtils(); // 渲染工具栏按钮

  // 选中的行数
  const selectedCount = computed(() => {
    const checkboxCount = gridRef.value?.getCheckboxRecords().length;
    const radioCount = gridRef.value?.getRadioRecord() ? 1 : 0;
    const count =
      checkboxCount == 0 ? (radioCount == 0 ? 0 : radioCount) : checkboxCount;
    return count;
  });

  // 获取选中的行
  const selectedRows = computed(() => {
    const checkboxRows = gridRef.value?.getCheckboxRecords();
    const radioRow = gridRef.value?.getRadioRecord();
    const rows = checkboxRows.length > 0 ? checkboxRows : [radioRow];
    return rows;
  });

  // 当前行数据
  const currentRow = computed(() => {
    return selectedRows.value[0];
  });

  // 数据库表选择
  const { showDBTableSelectorDialog } = useDBTableSelector();

  // ==================== 操作处理函数 ====================
  const useActionHandle = () => {
    const actions = {
      // add
      addHandle() {
        addRef.value?.show();
      },
      // update
      updateHandle(row) {
        updateRef.value.show(row.id);
      },
      // detail
      detailHandle(row) {
        detailRef.value.show(row.id);
      },
      // delete
      deleteHandle(row) {
        const confirmMessage = $t('common.message.confirm.general', {
          default: '您确定要执行',
          params: {
            action: $t('common.action.delete', '删除'),
          },
        });
        const content = `${confirmMessage} ：${row.id}`;
        VxeUI.modal.confirm(content).then((result) => {
          if (result === 'confirm') {
            API.delete({ id: row.id }).then(({ success }) => {
              success && gridRef.value.commitProxy('query');
            });
          }
        });
      },

      // 字段管理
      fieldHandle(row) {
        const target = $t('menu.dev.field.title', '字段管理');
        const menu = $t(row.key, row.name);
        const tag = `【${menu}-${target}】`;
        router.push({
          path: '/dev/field',
          name: 'DevField',
          query: {
            _parent: '/dev/menu',
            id: row.id,
            app: row.app,
            menu,
            tag,
          },
        });
      },

      // 方法管理
      actionHandle(row) {
        const target = $t('menu.dev.action.title', '方法管理');
        const menu = $t(row.key, row.name);
        const tag = `【${menu}-${target}】`;
        router.push({
          path: '/dev/action',
          name: 'DevAction',
          query: {
            _parent: '/dev/menu',
            id: row.id,
            app: row.app,
            menu,
            tag,
          },
        });
      },

      // 生成代码
      async genCodeHandle(row) {
        const overwrite = ref(true);
        const radioOptions = [
          { label: '覆盖源码', value: true },
          { label: '备份源码', value: false },
        ];
        try {
          const result = await VxeUI.modal.confirm({
            title: `为菜单 ${row.name || row.id} 生成代码`,
            width: 400,
            slots: {
              default: () => {
                return [
                  h('span', {}, '是否允许覆盖已存在的源码？'),
                  h(
                    ElRadioGroup,
                    {
                      modelValue: overwrite.value,
                      'onUpdate:modelValue': (value) => {
                        overwrite.value = value;
                      },
                    },
                    () =>
                      radioOptions.map((option) =>
                        h(ElRadio, {
                          label: option.label,
                          value: option.value,
                        }),
                      ),
                  ),
                ];
              },
            },
          });
          if (result === 'confirm') {
            const params = {
              id: row.id,
              overwrite: overwrite.value,
            };
            const { code, message } = await API.genCode(params);
            code === 200 && ElMessage.success(message);
          }
        } catch (error) {
          console.log(error.message);
          ElMessage.error(error.message);
        }
      },

      // 复制菜单
      async copyHandle(row) {
        const app = ref('admin');
        const radioOptions = [
          { label: '后台应用', value: 'admin' },
          { label: '前端应用', value: 'api' },
        ];
        try {
          // vxe-ui
          const result = await VxeUI.modal.confirm({
            title: `复制菜单 ${row.name || row.id} 到指定应用`,
            width: 400,
            slots: {
              default: () => {
                return h(
                  ElRadioGroup,
                  {
                    modelValue: app.value,
                    'onUpdate:modelValue': (value) => {
                      app.value = value;
                    },
                  },
                  () =>
                    radioOptions.map((option) =>
                      h(ElRadio, {
                        label: option.label,
                        value: option.value,
                      }),
                    ),
                );
              },
            },
          });
          if (result === 'confirm') {
            await API.copy({ id: row.id, app: app.value });
            if (app.value === 'api') {
              const result = await VxeUI.modal.confirm({
                title: '提示',
                content: '是否导航到接口菜单？',
                mask: false,
                lockView: false,
              });
              if (result === 'confirm') {
                router.push({ name: 'DevApi' });
              }
            }
            gridRef.value.commitProxy('query');
            ElMessage.success(
              $t('common.message.copy.success', '菜单复制成功'),
            );
          }
        } catch (error) {
          console.error('API call failed:', error);
        }
      },

      // 从表生成
      async fromTableHandle() {
        try {
          const { connect, table, level } = await showDBTableSelectorDialog({
            dialogTitle: $t('common.title.from_table', '从表生成菜单'),
            defaultConnect: null,
            defaultTable: null,
          });
          await API.fromTable({ connect, table, level });
          gridRef.value.commitProxy('query');
          ElMessage.success(
            $t('common.message.info.operate_success', '操作成功'),
          );
        } catch (error) {
          console.error('弹窗错误:', error);
        }
      },

      cleanHandle() {
        API.clean().then(({ data }) => {
          if (data.count == 0) {
            ElMessage.info('无可清理数据'); // 使用 Element-Plus 的 Message 提示
            return;
          }

          let tips = `即将清理${data.count}条数据，主要包括：\n\n`;
          tips += `菜单记录：\n${data.menu_names.join('，')}\n\n`;
          tips += `字段记录：\n${data.field_names.join('，')}\n\n`;
          tips += `方法记录：\n${data.action_names.join('，')}\n\n`;
          tips += `数据库表：\n${data.table_names.join('\n')}\n\n`;
          tips += '数据将会彻底清除，且不可恢复！您确定要清理数据吗？';

          // 构造带有滚动条的 HTML 内容
          const scrollableContent = h('div', {
            style: {
              'max-height': '200px',
              'overflow-y': 'auto',
              padding: '10px',
              'white-space': 'pre-wrap',
            },
            innerHTML: tips,
          });

          ElMessageBox.confirm(scrollableContent, '确认清理数据', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then(() => {
              API.clean({ confirm: 1 }).then(() => {
                ElMessage.success('清理成功');
                gridRef.value.commitProxy('query');
              });
            })
            .catch(() => {
              ElMessage.info('已取消清理');
            });
        });
      },

      // 结束
    };
    return actions;
  };
  // ==================== 列配置 ====================
  const useColumn = () => {
    const actions = useActionHandle();
    // 字段列
    const fieldColumn = computed(() => [
      {
        field: 'id',
        title: $t('common.field.id', '编号'),
        width: 50,
        align: 'center',
        visible: false,
      },
      {
        field: 'name',
        title: $t('menu.dev.menu.field.name', '名称'),
        treeNode: true,
        width: 160,
        slots: { default: 'nameDefault' },
      },
      {
        field: 'type',
        title: $t('menu.dev.menu.field.type', '类型'),
        align: 'center',
        width: 100,
        showOverflow: 'tooltip',
        cellRender: {
          name: 'RaDictSelectRender',
          code: 'sys_menu_type',
        },
      },
      {
        field: 'template',
        title: $t('menu.dev.menu.field.template', '页面模板'),
        align: 'center',
        width: 100,
        showOverflow: 'tooltip',
        cellRender: {
          name: 'RaDictSelectRender',
          code: 'sys_template',
        },
      },
      {
        field: 'controller',
        title: $t('menu.dev.menu.field.controller', '控制器'),
        align: 'left',
        width: 'auto',
        showOverflow: 'tooltip',
        formatter: ({ row }) => {
          if (row.controller) {
            return row.controller;
          } else {
            return '不适用';
          }
        },
      },
      {
        field: 'connect',
        title: $t('menu.dev.menu.field.connect', '连接'),
        align: 'left',
        visible: false,
        width: 'auto',
        showOverflow: 'tooltip',
        formatter: ({ row }) => {
          if (row.connect) {
            return row.connect;
          } else {
            return '不适用';
          }
        },
      },
      {
        field: 'table_name',
        title: $t('menu.dev.menu.field.table_name', '表名'),
        align: 'left',
        visible: true,
        width: 'auto',
        showOverflow: 'tooltip',
        formatter: ({ row }) => {
          if (row.table_name) {
            return row.table_name;
          } else {
            return '不适用';
          }
        },
      },
      {
        field: 'primary_key',
        title: $t('menu.dev.menu.field.primary_key', '主键'),
        align: 'left',
        visible: false,
        width: 'auto',
        showOverflow: 'tooltip',
        formatter: ({ row }) => {
          if (row.primary_key) {
            return row.primary_key;
          } else {
            return '不适用';
          }
        },
      },
      {
        field: 'route_name',
        title: $t('menu.dev.menu.field.route_name', '路由名称'),
        align: 'left',
        visible: false,
        width: 'auto',
        showOverflow: 'tooltip',
      },
      {
        field: 'route_path',
        title: $t('menu.dev.menu.field.route_path', '路由路径'),
        align: 'left',
        visible: false,
        width: 'auto',
        showOverflow: 'tooltip',
      },
      {
        field: 'component',
        title: $t('menu.dev.menu.field.component', '组件地址'),
        align: 'left',
        width: 'auto',
        showOverflow: 'tooltip',
        formatter: ({ row }) => {
          if (row.component) {
            return row.component;
          } else {
            return '不适用';
          }
        },
      },
      {
        field: 'remark',
        title: $t('common.field.remark', '备注'),
        align: 'left',
        visible: true,
        editRender: {
          enabled: hasAuth('dev:menu:modify'),
          name: 'ElInput',
        },
        showOverflow: 'tooltip',
      },
      {
        field: 'gen_table',
        title: $t('menu.dev.menu.field.gen_table', '创建表'),
        align: 'center',
        width: 'auto',
        showOverflow: 'tooltip',
        cellRender: {
          name: 'RaDictSwitchRender',
          code: 'yes_or_not_options',
        },
      },
      {
        field: 'gen_code',
        title: $t('menu.dev.menu.field.gen_code', '生成'),
        align: 'center',
        width: 'auto',
        showOverflow: 'tooltip',
        editRender: {
          enabled: hasAuth('dev:menu:modify'),
          name: 'RaDictSwitchRender',
          code: 'yes_or_not_options',
        },
      },
      {
        field: 'visible',
        title: $t('menu.dev.menu.field.visible', '显示'),
        align: 'center',
        width: 'auto',
        showOverflow: 'tooltip',
        editRender: {
          enabled: hasAuth('dev:menu:modify'),
          name: 'RaDictSwitchRender',
          code: 'yes_or_not_options',
        },
      },
      {
        field: 'status',
        title: $t('common.field.status', '状态'),
        align: 'center',
        width: 'auto',
        showOverflow: 'tooltip',
        editRender: {
          enabled: hasAuth('dev:menu:modify'),
          name: 'RaDictSwitchRender',
          code: 'status_options',
        },
      },
      {
        field: 'sort',
        title: $t('common.field.sort', '排序号'),
        align: 'left',
        width: 'auto',
        showOverflow: 'tooltip',
        sortable: true,
        dragSort: hasAuth('dev:menu:drag'),
      },

      // 结束
    ]);

    // 操作按钮
    const actionButtons = [
      // 字段按钮
      // {
      //   content: $t('common.action.field_mgr', '字段'),
      //   type: 'warning',
      //   icon: 'Memo',
      //   link: true,
      //   visible: hasAuth('dev:menu:field'),
      //   disabled: (row) => {
      //     return row.type != MenuTypeEnum.MENU;
      //   },
      //   onClick: (effectiveData) => {
      //     actions.fieldHandle(effectiveData);
      //   },
      // },

      // 方法按钮
      // {
      //   content: $t('common.action.action_mgr', '方法'),
      //   type: 'primary',
      //   icon: 'Operation',
      //   link: true,
      //   visible: hasAuth('dev:menu:action'),
      //   disabled: (row) => {
      //     return row.type != MenuTypeEnum.MENU;
      //   },
      //   onClick: (effectiveData) => {
      //     actions.actionHandle(effectiveData);
      //   },
      // },

      // 生成代码
      // {
      //   content: $t('common.action.gen_code', '生成'),
      //   type: 'danger',
      //   icon: 'Select',
      //   link: true,
      //   visible: hasAuth('dev:menu:gen_code'),
      //   disabled: (row) => {
      //     return row.type != MenuTypeEnum.MENU;
      //   },
      //   onClick: (effectiveData) => {
      //     actions.genCodeHandle(effectiveData);
      //   },
      // },

      // 更新
      {
        content: $t('common.action.update', '修改'),
        type: 'info',
        icon: 'Edit',
        link: true,
        visible: hasAuth('dev:menu:update'),
        disabled: (row) => {
          return row.type != MenuTypeEnum.MENU;
        },
        onClick: (effectiveData) => {
          actions.updateHandle(effectiveData);
        },
      },

      // 删除
      {
        content: $t('common.action.delete', '删除'),
        type: 'danger',
        icon: 'Delete',
        link: true,
        visible: hasAuth('dev:menu:delete'),
        onClick: (effectiveData) => {
          actions.deleteHandle(effectiveData);
        },
      },

      // 结束
    ];

    // 操作列
    const actionColumn = [
      {
        field: 'operation',
        title: $t('common.field.operation', '操作栏'),
        width: 'auto',
        align: 'center',
        fixed: 'right',
        visible: true,
        cellRender: {
          name: 'RaElButtonSetRender',
          buttons: actionButtons,
        },
      },

      // 结束
    ];

    // 使用 computed 属性来响应式地合并列配置
    const mergedColumns = computed(() => {
      let selectType = 'radio';
      const selectionColumn = [
        { field: 'selection', type: selectType, width: 50, align: 'center' },
      ];

      if (isSelectionMode.value) {
        return [...selectionColumn, ...fieldColumn.value];
      } else {
        return [...selectionColumn, ...fieldColumn.value, ...actionColumn];
      }
    });

    return mergedColumns;
  };

  /**
   * 表单配置
   *
   * @returns
   */
  const useFormConfig = () => {
    // 前端搜索字段配置
    const frontendData = {
      keyword: null,
      status: null,
    };

    // 前端搜索字段配置
    const frontendItems = computed(() => [
      {
        field: 'keyword',
        title: $t('common.field.keyword', '关键词'),
        folding: true,
        resetValue: null,
        itemRender: {
          name: 'ElInput',
          props: {
            placeholder: $p('common.field.keyword', '关键词'),
          },
        },
      },
      {
        field: 'status',
        title: $t('common.field.status', '状态'),
        folding: true,
        resetValue: null,
        itemRender: {
          name: 'RaDictSelectRender',
          code: 'status_options',
          multiple: false,
          clearable: true,
          placeholder: $p('common.field.status', '状态', 'select'),
        },
      },

      // 结束
    ]);

    // 操作按钮
    const actionButtons = {
      folding: true,
      align: 'left',
      itemRender: {
        name: 'RaElButtonSetRender',
        props: {
          buttons: [
            {
              nativeType: 'submit',
              content: $t('common.action.search', '搜索'),
              type: 'primary',
              icon: 'Search',
            },
            {
              nativeType: 'reset',
              content: $t('common.action.reset', '重置'),
              type: 'info',
              icon: 'Refresh',
            },

            // 结束
          ],
        },
      },
    };

    // 最终提供给组件的 formConfig，使用 computed 保证响应式
    const formConfig = computed(() => {
      return {
        span: formItemSpan.value,
        collapseStatus: showSearch.value,
        titleOverflow: true,
        titleBold: true,
        data: frontendData,
        items: [...frontendItems.value, actionButtons],
      };
    });

    return frontendItems.value.length > 0 ? formConfig : {};
  };

  /**
   * 工具栏配置
   *
   * @returns
   */
  const useToolbarConfig = () => {
    const buttons = [
      {
        name: $t('common.action.back', '返回'),
        code: 'return_code',
        status: 'info',
        icon: 'Back',
        visible: computed(() => {
          return isChildrenMode.value;
        }),
      },
      {
        name: $t('common.action.add', '新增'),
        code: 'add_code',
        status: 'success',
        icon: 'Plus',
        visible: hasAuth('dev:menu:add'),
      },
      {
        name: $t('common.action.update', '修改'),
        code: 'update_code',
        status: 'warning',
        icon: 'Edit',
        visible: hasAuth('dev:menu:update'),
        disabled: computed(() => {
          return selectedCount.value != 1;
        }),
      },
      {
        name: $t('common.action.detail', '详情'),
        code: 'detail_code',
        status: 'info',
        icon: 'View',
        visible: hasAuth('dev:menu:detail'),
        disabled: computed(() => {
          return selectedCount.value != 1;
        }),
      },
      {
        name: $t('common.action.delete', '删除'),
        code: 'delete_code',
        status: 'danger',
        icon: 'Delete',
        visible: hasAuth('dev:menu:delete'),
        disabled: computed(() => {
          return selectedCount.value === 0;
        }),
      },

      {
        name: $t('common.action.field_mgr', '字段'),
        code: 'field_code',
        status: 'default',
        icon: 'Memo',
        visible: hasAuth('dev:menu:field'),
        disabled: computed(
          () =>
            selectedCount.value !== 1 ||
            currentRow.value.type !== MenuTypeEnum.MENU,
        ),
      },
      {
        name: $t('common.action.action_mgr', '方法'),
        code: 'action_code',
        status: 'default',
        icon: 'Operation',
        visible: hasAuth('dev:menu:action'),
        disabled: computed(
          () =>
            selectedCount.value !== 1 ||
            currentRow.value.type !== MenuTypeEnum.MENU,
        ),
      },
      {
        name: $t('common.action.gen_code', '生成'),
        code: 'gen_code_code',
        status: 'default',
        icon: 'Select',
        visible: hasAuth('dev:menu:gen_code'),
        disabled: computed(() => {
          return selectedCount.value != 1;
        }),
      },
      {
        name: $t('common.action.copy', '复制'),
        code: 'copy_code',
        status: 'default',
        icon: 'CopyDocument',
        visible: hasAuth('dev:menu:copy'),
        disabled: computed(() => {
          return (
            selectedCount.value !== 1 ||
            currentRow.value.type !== MenuTypeEnum.MENU
          );
        }),
      },

      {
        name: $t('common.action.from_table', '从表生成'),
        code: 'from_table_code',
        status: 'default',
        icon: 'List',
        visible: hasAuth('dev:menu:from_table'),
      },
      {
        name: $t('common.action.clean', '清理'),
        code: 'clean_code',
        status: 'default',
        icon: 'DeleteFilled',
        visible: hasAuth('dev:menu:clean'),
      },

      // 结束
    ];

    const getToolbarConfig = () => {
      const toolbarConfig = {
        refresh: true,
        zoom: true,
        custom: true,
        buttons: renderToolbarButton(buttons),
        tools: [
          {
            code: 'search_code',
            circle: true,
            icon: computed(() => {
              return showSearch.value
                ? 'vxe-icon-arrow-down'
                : 'vxe-icon-arrow-up';
            }),
          },
        ],
      };
      return isSelectionMode.value ? {} : toolbarConfig;
    };

    return getToolbarConfig();
  };

  /**
   * 事件配置
   *
   * @returns
   */
  const useGridEvents = () => {
    const actions = useActionHandle();
    const events = {
      /**
       * 左侧工具栏按钮点击事件
       * @param {*} params
       */
      toolbarButtonClick(params) {
        // 获取选中的行
        const checkboxRows = gridRef.value?.getCheckboxRecords();
        const radioRow = gridRef.value?.getRadioRecord();
        const selectedRows =
          checkboxRows.length > 0 ? checkboxRows : [radioRow];

        // 根据不同code分别执行逻辑
        switch (params.code) {
          case 'return_code':
            utils.previousHandle(tagsViewStore, route, router);
            break;
          case 'add_code':
            actions.addHandle();
            break;
          case 'update_code':
            actions.updateHandle(selectedRows[0]);
            break;
          case 'delete_code':
            actions.deleteHandle(selectedRows[0]);
            break;
          case 'detail_code':
            actions.detailHandle(selectedRows[0]);
            break;
          case 'field_code':
            actions.fieldHandle(selectedRows[0]);
            break;
          case 'action_code':
            actions.actionHandle(selectedRows[0]);
            break;
          case 'gen_code_code':
            actions.genCodeHandle(selectedRows[0]);
            break;
          case 'copy_code':
            actions.copyHandle(selectedRows[0]);
            break;
          case 'clean_code':
            actions.cleanHandle();
            break;
          case 'from_table_code':
            actions.fromTableHandle();
            break;
        }
      },

      // 右键菜单事件
      menuClick({ menu, row }) {
        switch (menu.code) {
          case 'field_code':
            actions.fieldHandle(row);
            break;
          case 'action_code':
            actions.actionHandle(row);
            break;
          case 'gen_code_code':
            actions.genCodeHandle(row);
            break;
          case 'copy_code':
            actions.copyHandle(row);
            break;
          case 'from_table_code':
            actions.fromTableHandle();
            break;
        }
      },

      /**
       * 右侧工具栏点击事件
       * @param {*} params
       */
      toolbarToolClick(params) {
        switch (params.code) {
          case 'search_code':
            showSearch.value = !showSearch.value;
            break;
        }
      },
      /**
       * 行拖拽排序
       * @param {*} event
       */
      async rowDragend(event) {
        const params = utils.getDragParams(event, gridRef.value, 'sort');
        try {
          await API.drag(params);
          gridRef.value.commitProxy('query');
        } catch (error) {
          console.error('Drag sort failed:', error);
        }
      },

      /**
       * 单元格编辑关闭事件，实现单元格编辑保存功能
       * @param {*} param
       */
      async editClosed({ row, column }) {
        try {
          await API.modify({ id: row.id, [column.field]: row[column.field] });
          ElMessage.success('操作成功');
        } catch (error) {
          console.error('Edit closed failed:', error);
        }
      },

      /**
       * 单选框点选后,增加向父窗口传递参数
       * @param {*} param0
       */
      radioChange({ row }) {
        utils.radioChangeHandle(row, route);
      },

      /**
       * 复选框点选后,增加向父窗口传递参数
       * @param {*} param
       */
      checkboxChange({ records }) {
        utils.checkBoxChangeHandle(records, route);
      },

      /**
       * 复选框的全选,增加向父窗口传递参数
       * @param {*} param
       */
      checkboxAll({ records }) {
        utils.checkBoxChangeHandle(records, route);
      },
    };

    return { getGridEvents: async () => events };
  };

  /**
   * 代理配置
   *
   * @returns
   */
  const useProxyConfig = () => {
    const getProxyConfig = async () => {
      return {
        sort: true,
        form: true,
        // page: true,
        filter: true,
        response: {
          list: 'data',
          // result: 'data',
          // total: 'total',
        },
        ajax: {
          async query({ page, form, sorts, filters }) {
            // 合并表单参数和URL参数
            const queryParams = { ...form, ...route.query };
            // 排序参数
            if (sorts.length > 0) {
              console.log('sorts', sorts);
              queryParams.order_by = sorts
                .map((item) => `${item.field}|${item.order}`)
                .join(',');
            }
            // 分页参数
            // if (page) {
            //   queryParams.page_size = page.pageSize;
            //   queryParams.current_page = page.currentPage;
            // }
            // 过滤参数
            if (filters) {
              filters.map((item) => {
                queryParams[item.field] = item.values;
              });
            }
            try {
              const { data: result } = await API.index(queryParams);
              if (result.sort) {
                const sortRules = Object.entries(result.sort).map(
                  ([field, order]) => ({ field, order: order.toLowerCase() }),
                );
                gridRef.value.setSort(sortRules);
              }
              return result;
            } catch (error) {
              console.error('data loading failed:', error);
              throw error;
            }
          },
        },
      };
    };

    return { getProxyConfig };
  };

  /**
   * 主要配置函数
   */
  const columns = useColumn(); // 列配置
  const formConfig = useFormConfig(); // 表单配置
  const toolbarConfig = useToolbarConfig(); // 工具栏配置
  const { getProxyConfig } = useProxyConfig(); // 代理配置
  const { getGridEvents } = useGridEvents(); // 表格事件
  // 获取表格配置
  const getGridConfig = async () => {
    const options = {
      id: tableId,
      height: tableHeight,
      border: true,
      keepSource: false,
      rowConfig: {
        useKey: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
        drag: true,
      },
      columnConfig: {
        resizable: true,
      },
      resizableConfig: {
        dragMode: 'fixed',
        isDblclickAutoWidth: true,
        minWidth: 60,
      },
      customConfig: {
        storage: true,
      },
      editConfig: {
        trigger: 'dblclick',
        mode: 'cell',
        showStatus: false,
      },
      printConfig: {
        excludeFields: ['selection', 'operation'],
      },
      filterConfig: {
        remote: true,
      },
      sortConfig: {
        remote: true,
      },
      menuConfig: {
        body: {
          options: [
            [
              {
                code: 'from_table_code',
                name: $t('common.action.from_table', '从表生成'),
                prefixConfig: { icon: 'vxe-icon-subtable' },
                disabled: false,
              },
            ],
            [
              {
                code: 'field_code',
                name: $t('common.action.field_mgr', '字段'),
                prefixConfig: { icon: 'vxe-icon-row-col' },
                disabled: false,
              },
              {
                code: 'action_code',
                name: $t('common.action.action_mgr', '方法'),
                prefixConfig: { icon: 'vxe-icon-square-caret-right' },
                disabled: false,
              },
            ],
            [
              {
                code: 'gen_code_code',
                name: $t('common.action.gen_code', '生成'),
                prefixConfig: { icon: 'vxe-icon-lightning' },
                disabled: false,
              },
            ],
            [
              {
                code: 'copy_code',
                name: $t('common.action.copy', '复制'),
                prefixConfig: { icon: 'vxe-icon-copy' },
                disabled: false,
              },
            ],
          ],
        },
        visibleMethod({ options, row, column }) {
          const isDisabledDirectory = row && row.type === MenuTypeEnum.CATALOG;
          options.forEach((list) => {
            list.forEach((item) => {
              if (item.code !== 'from_table_code') {
                item.disabled = isDisabledDirectory;
              }
            });
          });
          return true;
        },
      },
      columns,
      formConfig,
      toolbarConfig,
      proxyConfig: await getProxyConfig(),
      // 合并自定义配置
      ...customConfig,
    };
    // 事件
    const events = await getGridEvents();
    // 返回表格配置和事件
    return { options, events };
  };

  onMounted(async () => {
    try {
      const { data } = await FieldAPI.getOptions();
      selectOption.value = data;
      const config = await getGridConfig();
      gridOptions.value = config.options;
      gridEvents.value = config.events;
    } catch (error) {
      console.error('vxe-grid initialization failed', error);
    }
  });

  return {
    // 表格引用和配置
    gridRef,
    gridOptions,
    gridEvents,
    // 附属组件的引用
    addRef,
    updateRef,
    detailRef,
    // 选择组件选项
    selectOption,
  };
};
